﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using Mvvm;
using Play.Messaging;
using Play.TrackManagement;
using Utils;

namespace Play.Shell.ViewModels
{
	public class MainViewModel : ViewModelBase
	{
		private readonly Func<SelectInstrumentViewModel> _selectInstrumentViewModelFactory;
		private readonly Func<Track, TrackViewModel> _trackViewModelFactory;

		public MainViewModel(
			Func<SelectInstrumentViewModel> selectInstrumentViewModelFactory,
			Func<Track, TrackViewModel> trackViewModelFactory)
		{
			_selectInstrumentViewModelFactory = selectInstrumentViewModelFactory;
			_trackViewModelFactory = trackViewModelFactory;
			ShowInstrumentsCommand = new RelayCommand(ShowInstruments);
		}

		public event MessageEventHandler SendMessage;

		public ICommand ShowInstrumentsCommand { get; private set; }

		private readonly ObservableCollection<TrackViewModel> _tracks = new ObservableCollection<TrackViewModel>();
		public IEnumerable<TrackViewModel> Tracks { get { return _tracks; } }

		private SelectInstrumentViewModel _selectInstrumentViewModel;
		public SelectInstrumentViewModel SelectInstrumentViewModel
		{
			get { return _selectInstrumentViewModel; }
			private set
			{
				_selectInstrumentViewModel = value;
				OnPropertyChanged(() => SelectInstrumentViewModel);
				OnPropertyChanged(() => InstrumentViewVisibility);
			}
		}

		public Visibility InstrumentViewVisibility
		{
			get
			{
				return _selectInstrumentViewModel != null
					? Visibility.Visible
					: Visibility.Collapsed;
			}
		}

		public void HandleMessage(TrackCreatedMessage message)
		{
			_tracks.Add(_trackViewModelFactory(message.Track));
		}

		public void HandleMessage(ShowTrackViewRequestMessage message)
		{
			SelectInstrumentViewModel = null;
		}

		private void ShowInstruments()
		{
			SelectInstrumentViewModel = _selectInstrumentViewModelFactory();
		}
	}
}
